package com.loooooo.pm2024.service;

import com.loooooo.pm2024.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;

@Service
public class FileDownloadService {

    @Autowired
    RestTemplate restTemplate;

    public int downloadPost(String url, File file) {
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        try {
            ResponseEntity<Resource> response = restTemplate.postForEntity(url, map, Resource.class);
            System.out.println(url);
            if (response.getStatusCodeValue() == 200) {
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                //System.out.println(response.getStatusCodeValue() + "\t" + response.getBody().getInputStream().available());
                IOUtils.copyInputStreamToFile(response.getBody().getInputStream(), file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    public int downloadGet(String url, File file) {
        try {
            ResponseEntity<Resource> response = restTemplate.getForEntity(url, Resource.class);
            System.out.println(url);
            if (response.getStatusCodeValue() == 200) {
                if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                //System.out.println(response.getStatusCodeValue() + "\t" + response.getBody().getInputStream().available());
                IOUtils.copyInputStreamToFile(response.getBody().getInputStream(), file);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

}
